# --------------------------------------------------------------------------
# Software:     InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright:    (C) 2001  Centro de Pesquisas Renato Archer
# Homepage:     http://www.softwarepublico.gov.br
# Contact:      invesalius@cti.gov.br
# License:      GNU - GPL 2 (LICENSE.txt/LICENCA.txt)
# --------------------------------------------------------------------------
#    Este programa e software livre; voce pode redistribui-lo e/ou
#    modifica-lo sob os termos da Licenca Publica Geral GNU, conforme
#    publicada pela Free Software Foundation; de acordo com a versao 2
#    da Licenca.
#
#    Este programa eh distribuido na expectativa de ser util, mas SEM
#    QUALQUER GARANTIA; sem mesmo a garantia implicita de
#    COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
#    PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
#    detalhes.
# --------------------------------------------------------------------------
import sys
import os
import vtk
import wx
import wx.lib.hyperlink as hl
from invesalius.pubsub import pub as Publisher
import wx.lib.foldpanelbar as fpb
import wx.lib.colourselect as csel

import invesalius.constants as const
import invesalius.data.slice_ as slice_
import invesalius.data.volume as volume
import invesalius.data.styles as styles
import invesalius.data.cursor_actors as curact
import invesalius.data.viewer_slice as viewer_slice

import invesalius.gui.dialogs as dlg
import wx.lib.platebtn as pbtn
import invesalius.project as prj
import invesalius.utils as utl

# INTERPOLATION_MODE_LIST = ["Cubic", "Linear", "NearestNeighbor"]
MIN_TRANSPARENCY = 0
MAX_TRANSPARENCY = 100

#############
BTN_NEW = wx.NewId()
MENU_SQUARE = wx.NewId()
MENU_CIRCLE = wx.NewId()


class TaskPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        inner_panel = InnerTaskPanel(self)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(inner_panel, 0, wx.EXPAND | wx.GROW | wx.BOTTOM | wx.RIGHT |
                  wx.LEFT, 7)
        sizer.Fit(self)

        self.SetSizer(sizer)
        self.Update()
        self.SetAutoLayout(1)

        # select mask - combo
        # mesh quality - combo?
        # apply button
        # Contour - slider
        # enable / disable Fill holes


class InnerTaskPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        # default_colour = self.GetBackgroundColour()
        backgroud_colour = wx.Colour(255, 255, 255)
        self.SetBackgroundColour(backgroud_colour)
        self.SetAutoLayout(1)
        # explain line-botton for select the axis/plane
        select_axis = wx.StaticText(self, -1, _("Select projection axis/plane"))
        # self.select_axis.Bind(wx.EVT_BUTTON,self.OnButtonForOrientate)
        # select_axis.Bind(wx.EVT_BUTTON,self.OnEnableTool)
        tooltip = wx.ToolTip(_("Select projection axis or plane on the surface"))
        select_axis.SetToolTip(tooltip)  # Add axis sizers into main sizer
        # select_text = wx.BoxSizer(wx.HORIZONTAL)
        # select_text.Add(select_axis,1, wx.EXPAND|wx.GROW| wx.TOP|wx.RIGHT, 4)
        # Add(wx.Window window, integer proportion=0, integer flag = 0, integer border = 0)
        # point 1
        self.point1_text = wx.ToggleButton(self, -1, _("Apex choose"))
        self.point1_text.Bind(wx.EVT_TOGGLEBUTTON, self.OnSelectApex)
        point1_tip = wx.ToolTip(_('The apex of heart'))
        self.point1_text.SetToolTip(point1_tip)
        point1_box = wx.BoxSizer(wx.HORIZONTAL)
        point1_box.Add(self.point1_text, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t1 = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
        point1_box.Add(self.t1, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t1.Bind(wx.EVT_TEXT_ENTER, self.OneKeyTyped)
        # point 2
        self.point2_text = wx.ToggleButton(self, -1, _("Base choose"))
        self.point2_text.Bind(wx.EVT_TOGGLEBUTTON, self.OnSelectBase)
        point2_box = wx.BoxSizer(wx.HORIZONTAL)
        point2_tip = wx.ToolTip(_('The base of the left ventricle'))
        self.point2_text.SetToolTip(point2_tip)
        point2_box.Add(self.point2_text, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t2 = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
        point2_box.Add(self.t2, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t2.Bind(wx.EVT_TEXT_ENTER, self.TwoKeyTyped)
        # number of slice
        section_num = wx.StaticText(self, -1, _('The number of slice'))
        section_num_box = wx.BoxSizer(wx.HORIZONTAL)
        section_num_box.Add(section_num, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t3 = wx.TextCtrl(self, value='14', style=wx.TE_PROCESS_ENTER)
        t3_tip = wx.ToolTip(_('Type "Enter" to confirm the input'))
        self.t3.SetToolTip(t3_tip)
        section_num_box.Add(self.t3, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, 5)
        self.t3.Bind(wx.EVT_TEXT_ENTER, self.GetSliceNumber)
        # button to Calculation
        self.button_jisuan = wx.Button(self, -1, _("Show the reference aixs"))
        self.button_jisuan.Enable(False)
        self.button_jisuan.Bind(wx.EVT_BUTTON, self.OnButtonShowAxis)

        self.Slice_cutButton = wx.Button(self, -1, _("Cut Plane and Show"))
        self.Slice_cutButton.Bind(wx.EVT_BUTTON, self.Slice_cutNextTask)
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(select_axis, 0, wx.ALIGN_LEFT | wx.LEFT | wx.TOP, 5)
        main_sizer.Add(point1_box)
        main_sizer.Add(point2_box)
        main_sizer.Add(section_num_box)
        main_sizer.Add(self.button_jisuan, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)
        main_sizer.Add(self.Slice_cutButton, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 5)
        main_sizer.Fit(self)

        self.SetSizerAndFit(main_sizer)
        self.Update()
        # self.SetAutoLayout(1)
        self.startpos = ()
        self.endpos = ()
        self.flagA = False
        self.flagB = False
        self.flag = 1
        self.sizer = main_sizer
        Publisher.subscribe(self.ChooseSeedPoints, 'Choose Point Result')

    # CutPlane(img, volume_mapper)
    # calculate projection
    def Button_Enable(self, event):
        if self.startpos and self.endpos:
            self.button_jisuan.Enable(True)
        else:
            self.button_jisuan.Enable(False)

    def OneKeyTyped(self, event):
        unipos = event.GetString()
        strpos = str(unipos).split(',')
        if len(strpos) == 3:
            posi = (float(strpos[0]), float(strpos[1]), float(strpos[2]))
            print('1stpos:', posi, type(posi))
            self.startpos = posi
            Publisher.sendMessage('textEnterEvent', (posi[0], posi[1], posi[2]))

    def TwoKeyTyped(self, event):
        unipos = event.GetString()
        strpos = str(unipos).split(',')
        if len(strpos) == 3:
            posi = (float(strpos[0]), float(strpos[1]), float(strpos[2]))
            print('2ndpos:', posi, type(posi))
            self.endpos = posi
            Publisher.sendMessage('textEnterEvent', (posi[0], posi[1], posi[2]))

    def ChooseSeedPoints(self, evt):
        value = evt.data
        print('flagA:', self.flagA)
        print('flagB:', self.flagB)
        if self.flagA and (not self.flagB):
            self.t1.Clear()
            self.t1.AppendText('%d,%d,%d' % (int(value[0]), int(value[1]), int(value[2])))
            self.startpos = (int(value[0]), int(value[1]), int(value[2]))
        if self.flagB and (not self.flagA):
            self.t2.Clear()
            self.t2.AppendText('%d,%d,%d' % (int(value[0]), int(value[1]), int(value[2])))
            self.endpos = (int(value[0]), int(value[1]), int(value[2]))

    def OnSelectApex(self, bind_event):
        self.flagA = self.point1_text.GetValue()
        if self.flagA:
            self.point2_text.SetValue(False)
            self.flagB = False
        if self.flagA and (not self.flagB):
            Publisher.sendMessage('Toggle Cross', const.SLICE_STATE_CROSS)
        if (not self.flagA) and (not self.flagB):
            Publisher.sendMessage('Toggle toolbar item', (const.SLICE_STATE_CROSS, False))
            Publisher.sendMessage('Disable style', const.SLICE_STATE_CROSS)

    def OnSelectBase(self, bind_event):
        self.flagB = self.point2_text.GetValue()
        if self.flagB:
            self.point1_text.SetValue(False)
            self.flagA = False
        if self.flagB and (not self.flagA):
            Publisher.sendMessage('Toggle Cross', const.SLICE_STATE_CROSS)
        if (not self.flagA) and (not self.flagB):
            Publisher.sendMessage('Toggle toolbar item', (const.SLICE_STATE_CROSS, False))
            Publisher.sendMessage('Disable style', const.SLICE_STATE_CROSS)
            self.button_jisuan.Enable(True)

    def OnButtonShowAxis(self, evt):
        if self.endpos and self.startpos:
            Publisher.sendMessage('Set line reference position', [self.startpos, self.endpos])
        else:
            print('please choose points first!')

    def Slice_cutNextTask(self, evt):
        if self.flag:
            # Publisher.sendMessage('Fold export task')
            Publisher.sendMessage('Show DataOut panel')
            evt.Skip()
            self.flag = 0
        else:
            Publisher.sendMessage('Hide DataOut panel')
            self.flag = 1

    def GetSliceNumber(self, event):
        print(int(event.GetString()))
        print(type(event.GetString))
